package taillog

import (
	"Study_go/LogAgent/etcd"
	"fmt"
	"time"
)

var tskMgr *TailMgr
type TailMgr struct{
	logEntry []*etcd.LogEntry
	tskMap map[string]*TailTask
	logEntryChan chan []*etcd.LogEntry
}

func Init(logEntryConf []*etcd.LogEntry){
	tskMgr = &TailMgr{
		logEntry:logEntryConf,
		tskMap:make(map[string]*TailTask,16),
		logEntryChan:make(chan []*etcd.LogEntry),//做一个单值管道，没有值的时候就阻塞
	}
	for _,v:=range logEntryConf{
		mk:=fmt.Sprintf("%s_%s",v.Path,v.Topic)

		tailojb:=NewTailTask(v.Path,v.Topic)
		tskMgr.tskMap[mk]=tailojb

	}
	go tskMgr.run()

}
//监听自己的logEntryChan，有新的配置项的时候进行处理
func (this *TailMgr) run(){
	for{
		select{
			case newconf:=<-this.logEntryChan:
				for _,v:=range newconf{
					mk:=fmt.Sprintf("%s_%s",v.Path,v.Topic)
					_,ok:=this.tskMap[mk]
					if ok{
						//原先已经有了
						continue
					}else{
						//原先没有，需要新增
						tailojb:=NewTailTask(v.Path,v.Topic)
						this.tskMap[mk]=tailojb
					}
				}
				for _,c1:=range this.logEntry{
					isDelete := true
					for _,c2:=range newconf{
						if c1.Path==c2.Path&&c1.Topic==c2.Topic{
							//原先已经有了，则不需要删除
							isDelete = false
							continue
						}
					}
					if isDelete{
						//删除配置
						mk:=fmt.Sprintf("%s_%s",c1.Path,c1.Topic)
						this.tskMap[mk].cancelFunc()
					}
				}
				//删除配置
				//fmt.Println("新的配置项来了：",newconf)
			default:
				time.Sleep(time.Second)

		}
	}
}

//向外暴露logEntryChan
func ExportlogEntryChan() chan<- []*etcd.LogEntry{
	return tskMgr.logEntryChan
}